package com.icode.util;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Author: my_code
 * @Email: my_code@foxmail.com
 * @Create: 2020-12-12 15:31
 */
public class SemaphoreTest {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(4);

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "拿到信号量许可证");
                    //延时几秒
                    try {
                        TimeUnit.SECONDS.sleep(2);
                        System.out.println("==============");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println(Thread.currentThread().getName() + "释放信号量许可证");
                    semaphore.release();
                }
            }, String.valueOf(i)).start();

        }
    }
}
